package com.juzhencms.apps.busi.web;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.base.busi.service.UploadService;
import com.juzhencms.apps.base.busi.service.UploadService.UploadResult;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.HtmlUtil;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;
import com.juzhencms.apps.busi.service.AppResourceCategoryService;


@Controller
@RequestMapping("/appResource")
public class AppResourceController  extends BaseController{
	
	@Autowired
	private UploadService uploadService;
	@Autowired
	private AppResourceCategoryService appResourceCategoryService;
	
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		String where="where del_flag=0";
		
		//限定展示的数据范围
		if(request.getParameter("dataRange")!=null && !request.getParameter("dataRange").toString().trim().equals("")){
			if(request.getParameter("dataRange").equals("myorg")) {//本部门数据
				//默认查看本部门的数据
				where+=" and org_id = ? ";
				whereParamList.add(this.getLoginUser().getOrgId());
				
				//log.info("getOrgId:"+this.getLoginUser().getOrgId());
				
				
			}else if(request.getParameter("dataRange").equals("useable")) {//全部可用数据，本部门+其他部门的公开数据
				where+=" and (org_id = ? or share=1) ";
				whereParamList.add(this.getLoginUser().getOrgId());
			}else if(request.getParameter("dataRange").equals("suborg")){//下级部门数据
				where+=" and org_id != ? and org_id in("+this.getLoginUser().getSubOrgIds()+") ";
				whereParamList.add(this.getLoginUser().getOrgId());
			}
		}else {
			//默认查看本部门的数据
			where+=" and org_id = ? ";
			whereParamList.add(this.getLoginUser().getOrgId());
		}
		
		
		//搜索参数
		if(request.getParameter("name")!=null && !request.getParameter("name").toString().trim().equals("")){
			where+=" and name like ? ";
			whereParamList.add("%"+request.getParameter("name")+"%");
		}		
		if(request.getParameter("publish")!=null && !request.getParameter("publish").toString().trim().equals("")){
			where+=" and publish = ? ";
			whereParamList.add(request.getParameter("publish"));
		}
		
		if(request.getParameter("create_time_from")!=null && !request.getParameter("create_time_from").toString().trim().equals("")){
			where+=" and create_time >= ? ";
			whereParamList.add(request.getParameter("create_time_from"));
		}
		
		if(request.getParameter("create_time_to")!=null && !request.getParameter("create_time_to").toString().trim().equals("")){
			where+=" and create_time <= ? ";
			whereParamList.add(request.getParameter("create_time_to"));
		}
		if(StringUtil.isNotNullOrEmpty(request.getParameter("category_id"))) {
			where+=" and category_id = ? ";
			whereParamList.add(request.getParameter("category_id"));
		}
		
		//分页处理
		int pageIndex=1;
		if(request.getParameter("pageIndex")!=null && !request.getParameter("pageIndex").toString().trim().equals("")){
			pageIndex=new Integer(request.getParameter("pageIndex")).intValue();
		}
		int pageSize=10;
		if(request.getParameter("pageSize")!=null && !request.getParameter("pageSize").toString().trim().equals("")){
			pageSize=new Integer(request.getParameter("pageSize")).intValue();
		}
		int start=0;
		if(pageIndex>1){
			start=(pageIndex-1)*pageSize;
		}
		whereParamList.add(start);
		whereParamList.add(pageSize);
		
		//排序参数 
		String sortField="position";
		String sortOrder="asc";
		if(request.getParameter("sortField")!=null && !request.getParameter("sortField").equals(""))
			sortField = request.getParameter("sortField");
		if(request.getParameter("sortOrder")!=null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");
		
		
		List appResourceCategoryVar = this.appResourceCategoryService.listVarData();
		
		
		//查询列表数据
		List dataList=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.appResource+" "+where+" order by "+sortField+" "+sortOrder+" limit ?,?", whereParamList.toArray());
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				if(row.get("create_time")!=null) {
					Date date = (Date)row.get("create_time");
					row.put("create_time",sdf.format(date));
					String text=this.getDictionaryService().getText(appResourceCategoryVar, row.get("category_id")+"");
					row.put("category_name", text);
				}
				
				if(row.get("content")!=null) {
					//去掉素材中的空行
					row.put("content", row.get("content").toString().replace("<p><br/></p>", ""));
				}
				
				
				
			}
		}
		
		//查询总条数
		Map countRow=this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.appResource+" "+where, whereParamList.subList(0, whereParamList.size()-2).toArray());
		int recordsTotal=0;
		if(countRow.get("count_num")!=null){
			recordsTotal=new Integer(countRow.get("count_num").toString()).intValue();
		}
		
		//拼装返回的数据
		data.put("data", dataList.toArray());
		data.put("itemsCount", recordsTotal);
		
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/detailData/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(@PathVariable("id") String id,HttpServletRequest request){
		Map data=new HashMap();
		Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.appResource+" where id=?",new Object[]{id});	

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = (Date)record.get("create_time");
		record.put("create_time",sdf.format(date) );
		data.put("data", record);
		
		//获取最新版本数据
		Map lastHistory=this.getDataHistoryService().getLastValidVersion(DBTable.appResource, Integer.parseInt(id));
		if(lastHistory!=null) {
			if(lastHistory.get("params")!=null) {
				//使用最新的版本字段替换掉当前主表字段进行显示
				Map param=JSON.parseObject(lastHistory.get("params").toString(),Map.class);
				if(param!=null) {
					for(Object key : param.keySet()) {
						if(param.get(key)!=null) {
							record.put(key, param.get(key));
						}
					}
				}
				lastHistory.remove("params");
			}
			data.put("lastHistory", lastHistory);
		}
		
		if(record.get("content")!=null) {
			data.put("previewContent", this.getDataHistoryService().removeEditMark(record.get("content").toString()));
		}
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/save",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request){
		
		boolean draft=false;
		
		if(request.getParameter("draft")!=null && request.getParameter("draft").equals("1")) {
			draft=true;
		}
		
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		
		int id=0;
		if(data.get("id")!=null){
			id=new Long(data.get("id").toString()).intValue();
		}
		
		//敏感词检查
		String sensitiveKeywords=this.filterSensitiveKeywords(DBTable.appResource, data);
		if(sensitiveKeywords!=null) {
			Map result=new HashMap();
			result.put("result", 0);
			result.put("id", id);
			result.put("msg", "内容中包含敏感关键词:<font style='color:#F00'>"+sensitiveKeywords+"</font>,请修改后再提交");
			return WebUtil.resultString(result,request);
		}
		
		//执行图片本地化
		if(data.get("content")!=null) {
			String html=data.get("content").toString();
			Set<String> imgs=HtmlUtil.getImgStr(html);
			boolean replaceImg=false;
			for(String imgUrl:imgs) {
				if(imgUrl.indexOf(Config.getUploadUrlPath())!=0){
					//执行图片本地化
					UploadResult uploadResult=uploadService.uploadFileByUrl(imgUrl);
					if(uploadResult.getResult()==1) {
						//替换图片url
						html=html.replace(imgUrl, uploadResult.getUrlPath());
						replaceImg=true;
					}
					
				}
			}
			if(replaceImg) {
				data.put("content", html);
			}
		}
		
		if(id==0){
			if(data.get("create_time")==null || data.get("create_time").equals("")){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = new Date();
				data.put("create_time", sdf.format(date));
			}
			
			
			if(draft) {
				id=this.getDataHistoryService().saveDraftData(DBTable.appResource, data,"appResource");
			}else {
				id=this.getDataHistoryService().saveCheckData(DBTable.appResource, data,"appResource");
			}
			
			data.put("id", id);
		}else{
			if(draft) {
				this.getDataHistoryService().saveDraftData(DBTable.appResource, data,"appResource");
			}else {
				this.getDataHistoryService().saveCheckData(DBTable.appResource, data,"appResource");
			}
		}
		
		
		
		
		Map result=new HashMap();
		result.put("result", 1);
		result.put("id", id);
		result.put("msg", "保存成功");
		
		
		return WebUtil.resultString(result,request);
		
	}
	
	@RequestMapping(value="/delete",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String delete(HttpServletRequest request){

		
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		
		
		if(id==null || id.equals("")){
		}else{	
	        String[] idArray = id.split(",");
	        /*String tmpVar="?";
	        if(idArray!=null && idArray.length>0){
	        	Matcher matcher = Pattern.compile("\\d+").matcher(id);
	        	tmpVar=matcher.replaceAll("?");
	        }
			this.getCommonService().getJdbcDao().updateSql("update "+DBTable.appResource+" set del_flag=1 where id in ("+tmpVar+")",idArray);*/
	        for(int i=0;i<idArray.length;i++) {
	        	String value=idArray[i];
	        	if(value!=null && !value.equals("")) {
	        		this.getDataHistoryService().deleteData(DBTable.appResource, Integer.parseInt(value));
	        	}
	        }
		}
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	@RequestMapping(value="/updatePosition",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String updatePosition(HttpServletRequest request){
		
		if(request.getParameter("position")==null || request.getParameter("id")=="")
			return "";
		
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.appResource+" set position=? where id=?",new Object[]{request.getParameter("position"),request.getParameter("id")});
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	@RequestMapping(value="/getCategoryTreeList",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String getCategoryTreeList(HttpServletRequest request){
		
		List dataList=this.getMenuTree( 0);
		Map data=new HashMap();
		data.put("data", dataList);
		return WebUtil.resultString(data,request);
	}
	
	private List getMenuTree(int pid){
		//System.out.println(id);
		List dataList=this.getCommonService().getJdbcDao().querySql("select id,name from "+DBTable.appResourceCategory+" where pid=?  and del_flag = 0 order by position asc,id asc",new Object[]{pid});
		for(int i=0;i<dataList.size();i++){
			Map menu=(Map)dataList.get(i);
			List subList=this.getMenuTree(new Integer(menu.get("id").toString()));
			if(subList!=null && subList.size()>0)
				menu.put("children", subList);
		}
		return dataList;
	}
	
	@RequestMapping(value="/getAppResourceHtml/{type}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String getAppResourceHtml(@PathVariable("type") String type,HttpServletRequest request) {
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		String where="where del_flag=0 and publish=1  and category_id=? ";
		whereParamList.add(type);
		//搜索参数
		if(request.getParameter("name")!=null && !request.getParameter("name").toString().trim().equals("")){
			where+=" and name like ? ";
			whereParamList.add("%"+request.getParameter("name")+"%");
		}			
		
		
		//限定展示的数据范围
		if(request.getParameter("dataRange")!=null && !request.getParameter("dataRange").toString().trim().equals("")){
			
			if(request.getParameter("dataRange").equals("myorg")) {//本部门数据
				//默认查看本部门的数据
				where+=" and org_id = ? ";
				whereParamList.add(this.getLoginUser().getOrgId());
				
			}else if(request.getParameter("dataRange").equals("useable")) {//全部可用数据，本部门+其他部门的公开数据
				where+=" and (org_id = ? or share=1) ";
				whereParamList.add(this.getLoginUser().getOrgId());
			}else if(request.getParameter("dataRange").equals("suborg")){//下级部门数据
				where+=" and org_id != ? and org_id in("+this.getLoginUser().getSubOrgIds()+") ";
				whereParamList.add(this.getLoginUser().getOrgId());
			}
			
			
		}else {
			//默认查看本部门的数据
			where+=" and org_id = ? ";
			whereParamList.add(this.getLoginUser().getOrgId());
		}
				
		
		//分页处理
		int pageIndex=1;
		if(request.getParameter("pageIndex")!=null && !request.getParameter("pageIndex").toString().trim().equals("")){
			pageIndex=new Integer(request.getParameter("pageIndex")).intValue();
		}
		int pageSize=10;
		if(request.getParameter("pageSize")!=null && !request.getParameter("pageSize").toString().trim().equals("")){
			pageSize=new Integer(request.getParameter("pageSize")).intValue();
		}
		int start=0;
		if(pageIndex>1){
			start=(pageIndex-1)*pageSize;
		}
		whereParamList.add(start);
		whereParamList.add(pageSize);
		
		//排序参数 
		String sortField="position";
		String sortOrder="asc";
		if(request.getParameter("sortField")!=null && !request.getParameter("sortField").equals(""))
			sortField = request.getParameter("sortField");
		if(request.getParameter("sortOrder")!=null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");
		
		List appResourceCategoryVar = this.appResourceCategoryService.listVarData();
		//查询列表数据
		List dataList=this.getCommonService().getJdbcDao().querySql("select content from "+DBTable.appResource+" "+where+" order by "+sortField+" "+sortOrder+" limit ?,?", whereParamList.toArray());
		String dataHTML="";
		if(dataList!=null && dataList.size()>0){
			 dataHTML+="<ul class=\"template-list\">";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				if(StringUtil.isNotNullOrEmpty(row.get("content"))) {
					dataHTML+="<li title=\"点击插入此内容\">"+	row.get("content")+"</li>";
				}
			}
			 dataHTML+="</ul>";
		}
		Map result=new HashMap();
		result.put("result", 1);
		
		result.put("dataHtml", dataHTML);		
		return WebUtil.resultString(result,request);
	}
	
}
